<template>
  <div class="merchant-settlement">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>结算规则管理</span>
          <el-button type="primary" @click="handleAdd">新增规则</el-button>
        </div>
      </template>

      <!-- 搜索栏 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="商家类型">
          <el-select
            v-model="searchForm.type"
            placeholder="请选择商家类型"
            clearable
          >
            <el-option label="景点" value="scenic" />
            <el-option label="酒店" value="hotel" />
            <el-option label="餐饮" value="restaurant" />
            <el-option label="购物" value="shopping" />
          </el-select>
        </el-form-item>
        <el-form-item label="结算周期">
          <el-select
            v-model="searchForm.cycle"
            placeholder="请选择结算周期"
            clearable
          >
            <el-option label="T+1" value="T1" />
            <el-option label="T+3" value="T3" />
            <el-option label="每周" value="weekly" />
            <el-option label="每月" value="monthly" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 结算规则列表 -->
      <el-table :data="ruleList" border v-loading="loading">
        <el-table-column type="expand">
          <template #default="props">
            <el-form label-position="left" inline class="rule-detail">
              <el-form-item label="保证金规则">
                {{ props.row.depositRule }}
              </el-form-item>
              <el-form-item label="退款规则">
                {{ props.row.refundRule }}
              </el-form-item>
              <el-form-item label="特殊说明">
                {{ props.row.specialNotes }}
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="商家类型" width="100">
          <template #default="scope">
            <el-tag :type="getMerchantTypeTag(scope.row.type)">
              {{ getMerchantTypeLabel(scope.row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="规则名称" min-width="150" />
        <el-table-column prop="cycle" label="结算周期" width="100">
          <template #default="scope">
            <el-tag>{{ scope.row.cycle }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="commission" label="佣金比例" width="120">
          <template #default="scope"> {{ scope.row.commission }}% </template>
        </el-table-column>
        <el-table-column prop="minAmount" label="最低结算金额" width="120">
          <template #default="scope"> ¥{{ scope.row.minAmount }} </template>
        </el-table-column>
        <el-table-column prop="depositAmount" label="保证金" width="120">
          <template #default="scope"> ¥{{ scope.row.depositAmount }} </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 'active' ? 'success' : 'info'">
              {{ scope.row.status === "active" ? "启用" : "停用" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button-group>
              <el-button type="primary" link @click="handleEdit(scope.row)">
                编辑
              </el-button>
              <el-button
                type="primary"
                link
                @click="handleToggleStatus(scope.row)"
              >
                {{ scope.row.status === "active" ? "停用" : "启用" }}
              </el-button>
              <el-button type="danger" link @click="handleDelete(scope.row)">
                删除
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 规则编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑规则' : '新增规则'"
      width="700px"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="120px"
      >
        <el-tabs v-model="activeTab">
          <!-- 基本信息 -->
          <el-tab-pane label="基本信息" name="basic">
            <el-form-item label="规则名称" prop="name">
              <el-input v-model="formData.name" placeholder="请输入规则名称" />
            </el-form-item>
            <el-form-item label="商家类型" prop="type">
              <el-select v-model="formData.type" placeholder="请选择商家类型">
                <el-option label="景点" value="scenic" />
                <el-option label="酒店" value="hotel" />
                <el-option label="餐饮" value="restaurant" />
                <el-option label="购物" value="shopping" />
              </el-select>
            </el-form-item>
            <el-form-item label="结算周期" prop="cycle">
              <el-select v-model="formData.cycle" placeholder="请选择结算周期">
                <el-option label="T+1" value="T1" />
                <el-option label="T+3" value="T3" />
                <el-option label="每周" value="weekly" />
                <el-option label="每月" value="monthly" />
              </el-select>
            </el-form-item>
            <el-form-item label="佣金比例" prop="commission">
              <el-input-number
                v-model="formData.commission"
                :min="0"
                :max="100"
                :precision="2"
                :step="0.1"
                style="width: 100%"
              >
                <template #suffix>%</template>
              </el-input-number>
            </el-form-item>
            <el-form-item label="最低结算金额" prop="minAmount">
              <el-input-number
                v-model="formData.minAmount"
                :min="0"
                :step="100"
                controls-position="right"
                style="width: 100%"
              >
                <template #prefix>¥</template>
              </el-input-number>
            </el-form-item>
          </el-tab-pane>

          <!-- 保证金设置 -->
          <el-tab-pane label="保证金设置" name="deposit">
            <el-form-item label="保证金金额" prop="depositAmount">
              <el-input-number
                v-model="formData.depositAmount"
                :min="0"
                :step="1000"
                controls-position="right"
                style="width: 100%"
              >
                <template #prefix>¥</template>
              </el-input-number>
            </el-form-item>
            <el-form-item label="保证金规则" prop="depositRule">
              <el-input
                type="textarea"
                v-model="formData.depositRule"
                :rows="4"
                placeholder="请输入保证金规则说明"
              />
            </el-form-item>
            <el-form-item label="退还条件" prop="depositReturnConditions">
              <el-checkbox-group v-model="formData.depositReturnConditions">
                <el-checkbox label="contract_expired">合同到期</el-checkbox>
                <el-checkbox label="no_complaints">无有效投诉</el-checkbox>
                <el-checkbox label="good_credit">信用良好</el-checkbox>
                <el-checkbox label="settlement_complete">结算完成</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>

          <!-- 退款规则 -->
          <el-tab-pane label="退款规则" name="refund">
            <el-form-item label="退款时限" prop="refundTimeLimit">
              <el-input-number
                v-model="formData.refundTimeLimit"
                :min="1"
                :step="1"
                controls-position="right"
                style="width: 100%"
              >
                <template #suffix>天</template>
              </el-input-number>
            </el-form-item>
            <el-form-item label="退款规则" prop="refundRule">
              <el-input
                type="textarea"
                v-model="formData.refundRule"
                :rows="4"
                placeholder="请输入退款规则说明"
              />
            </el-form-item>
          </el-tab-pane>

          <!-- 其他设置 -->
          <el-tab-pane label="其他设置" name="other">
            <el-form-item label="特殊说明" prop="specialNotes">
              <el-input
                type="textarea"
                v-model="formData.specialNotes"
                :rows="4"
                placeholder="请输入特殊说明"
              />
            </el-form-item>
            <el-form-item label="规则状态" prop="status">
              <el-radio-group v-model="formData.status">
                <el-radio label="active">启用</el-radio>
                <el-radio label="inactive">停用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import service from "@/api/axios";

// 搜索表单
const searchForm = reactive({
  type: "",
  cycle: "",
});

// 列表数据
const loading = ref(false);
const ruleList = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);

// 测试数据
const testRuleList = [
  {
    id: 1,
    name: "景点标准结算规则",
    type: "scenic",
    cycle: "T+1",
    commission: 5.0,
    minAmount: 100,
    depositAmount: 5000,
    depositRule: "景点商家入驻需缴纳5000元保证金，合作满3个月且无违规记录可申请退还。",
    depositReturnConditions: ["contract_expired", "no_complaints", "good_credit"],
    refundTimeLimit: 7,
    refundRule: "游客可在游玩前7天申请全额退款，3-7天内退款收取10%手续费，3天内不予退款。",
    specialNotes: "法定节假日客流量大，建议提前做好人员安排。",
    status: "active"
  },
  {
    id: 2,
    name: "酒店月结规则",
    type: "hotel",
    cycle: "monthly",
    commission: 8.0,
    minAmount: 500,
    depositAmount: 10000,
    depositRule: "酒店商家入驻需缴纳10000元保证金，合作满6个月且无违规记录可申请退还50%，满一年可全额退还。",
    depositReturnConditions: ["contract_expired", "no_complaints", "good_credit", "settlement_complete"],
    refundTimeLimit: 3,
    refundRule: "顾客可在入住前3天申请全额退款，1-3天内退款收取首晚房费，当天不退款。",
    specialNotes: "酒店需保证图片与实际环境一致，如有差异需及时更新。",
    status: "active"
  },
  {
    id: 3,
    name: "餐饮商家结算规则",
    type: "restaurant",
    cycle: "T+3",
    commission: 10.0,
    minAmount: 200,
    depositAmount: 3000,
    depositRule: "餐饮商家入驻需缴纳3000元保证金，合作满3个月且无投诉可申请退还。",
    depositReturnConditions: ["contract_expired", "no_complaints"],
    refundTimeLimit: 1,
    refundRule: "顾客可在就餐前1天申请全额退款，当天退款需收取30%手续费。",
    specialNotes: "餐饮商家需确保食品安全，定期提交卫生检查报告。",
    status: "active"
  },
  {
    id: 4,
    name: "购物商家结算规则",
    type: "shopping",
    cycle: "weekly",
    commission: 12.0,
    minAmount: 300,
    depositAmount: 5000,
    depositRule: "购物商家入驻需缴纳5000元保证金，合作满6个月且无违规可申请退还。",
    depositReturnConditions: ["contract_expired", "good_credit"],
    refundTimeLimit: 7,
    refundRule: "顾客可在收到商品7天内无理由退货，商品需保持原样且不影响二次销售。",
    specialNotes: "商品描述需与实际一致，不得有虚假宣传。",
    status: "inactive"
  }
];

// 对话框相关
const dialogVisible = ref(false);
const isEdit = ref(false);
const activeTab = ref("basic");
const formRef = ref(null);

// 表单数据
const formData = reactive({
  name: "",
  type: "",
  cycle: "",
  commission: 0,
  minAmount: 0,
  depositAmount: 0,
  depositRule: "",
  depositReturnConditions: [],
  refundTimeLimit: 7,
  refundRule: "",
  specialNotes: "",
  status: "active",
});

// 表单验证规则
const rules = {
  name: [{ required: true, message: "请输入规则名称", trigger: "blur" }],
  type: [{ required: true, message: "请选择商家类型", trigger: "change" }],
  cycle: [{ required: true, message: "请选择结算周期", trigger: "change" }],
  commission: [{ required: true, message: "请输入佣金比例", trigger: "blur" }],
  minAmount: [
    { required: true, message: "请输入最低结算金额", trigger: "blur" },
  ],
  depositAmount: [
    { required: true, message: "请输入保证金金额", trigger: "blur" },
  ],
  depositRule: [
    { required: true, message: "请输入保证金规则", trigger: "blur" },
  ],
  refundTimeLimit: [
    { required: true, message: "请输入退款时限", trigger: "blur" },
  ],
  refundRule: [{ required: true, message: "请输入退款规则", trigger: "blur" }],
};

// 获取规则列表
const fetchRuleList = async () => {
  loading.value = true;
  try {
    // 调用获取规则列表API
    const res = await service.get('/admin/merchants/settlement/rules', {
      params: {
        page: currentPage.value,
        pageSize: pageSize.value,
        type: searchForm.type,
        cycle: searchForm.cycle
      }
    });
    
    if (res && res.code === 200) {
      ruleList.value = res.data.list || [];
      total.value = res.data.total || 0;
    } else {
      // 如果API调用失败，使用测试数据
      ruleList.value = testRuleList;
      total.value = testRuleList.length;
    }
  } catch (error) {
    console.error("获取规则列表失败：", error);
    ElMessage.error("获取规则列表失败，使用测试数据");
    
    // 使用测试数据
    ruleList.value = testRuleList;
    total.value = testRuleList.length;
  } finally {
    loading.value = false;
  }
};

// 搜索方法
const handleSearch = () => {
  currentPage.value = 1;
  fetchRuleList();
};

// 重置搜索
const resetSearch = () => {
  Object.assign(searchForm, {
    type: "",
    cycle: "",
  });
  handleSearch();
};

// 分页方法
const handleSizeChange = (val) => {
  pageSize.value = val;
  fetchRuleList();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  fetchRuleList();
};

// 新增规则
const handleAdd = () => {
  isEdit.value = false;
  dialogVisible.value = true;
  activeTab.value = "basic";
  Object.assign(formData, {
    name: "",
    type: "",
    cycle: "",
    commission: 0,
    minAmount: 0,
    depositAmount: 0,
    depositRule: "",
    depositReturnConditions: [],
    refundTimeLimit: 7,
    refundRule: "",
    specialNotes: "",
    status: "active",
  });
};

// 编辑规则
const handleEdit = async (row) => {
  try {
    loading.value = true;
    
    // 获取规则详情
    const res = await service.get(`/admin/merchants/settlement/rules/${row.id}`);
    
    if (res && res.code === 200) {
      // 使用API返回的详细数据
      Object.assign(formData, res.data);
    } else {
      // 如果API调用失败，使用传入的行数据
      Object.assign(formData, row);
    }
    
    isEdit.value = true;
    dialogVisible.value = true;
    activeTab.value = "basic";
  } catch (error) {
    console.error("获取规则详情失败：", error);
    ElMessage.error("获取规则详情失败");
    
    // 使用传入的行数据
    Object.assign(formData, row);
    isEdit.value = true;
    dialogVisible.value = true;
    activeTab.value = "basic";
  } finally {
    loading.value = false;
  }
};

// 切换状态
const handleToggleStatus = async (row) => {
  try {
    const newStatus = row.status === 'active' ? 'inactive' : 'active';
    
    const res = await service.post('/admin/merchants/settlement/rules/toggle-status', {
      id: row.id,
      status: newStatus
    });
    
    if (res && res.code === 200) {
      ElMessage.success("状态更新成功");
      fetchRuleList();
    } else {
      ElMessage.error(res?.message || "状态更新失败");
    }
  } catch (error) {
    console.error("状态更新失败：", error);
    ElMessage.error("状态更新失败");
  }
};

// 删除规则
const handleDelete = (row) => {
  ElMessageBox.confirm("确认删除该规则吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    try {
      const res = await service.delete(`/admin/merchants/settlement/rules/${row.id}`);
      
      if (res && res.code === 200) {
        ElMessage.success("删除成功");
        fetchRuleList();
      } else {
        ElMessage.error(res?.message || "删除失败");
      }
    } catch (error) {
      console.error("删除失败：", error);
      ElMessage.error("删除失败");
    }
  }).catch(() => {
    // 用户取消操作
  });
};

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return;
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        let res;
        
        if (isEdit.value) {
          // 更新规则
          res = await service.put(`/admin/merchants/settlement/rules/${formData.id}`, formData);
        } else {
          // 创建规则
          res = await service.post('/admin/merchants/settlement/rules', formData);
        }
        
        if (res && res.code === 200) {
          ElMessage.success("保存成功");
          dialogVisible.value = false;
          fetchRuleList();
        } else {
          ElMessage.error(res?.message || "保存失败");
        }
      } catch (error) {
        console.error("保存失败：", error);
        ElMessage.error("保存失败");
      }
    }
  });
};

// 获取商家类型标签
const getMerchantTypeTag = (type) => {
  const typeMap = {
    scenic: "success",
    hotel: "primary",
    restaurant: "warning",
    shopping: "info",
  };
  return typeMap[type];
};

// 获取商家类型标签文本
const getMerchantTypeLabel = (type) => {
  const labelMap = {
    scenic: "景点",
    hotel: "酒店",
    restaurant: "餐饮",
    shopping: "购物",
  };
  return labelMap[type];
};

// 页面初始化
onMounted(() => {
  fetchRuleList();
});
</script>

<style scoped>
.merchant-settlement {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.rule-detail {
  padding: 20px;
}

.rule-detail :deep(.el-form-item) {
  margin-bottom: 20px;
  width: 45%;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
